package com.agent.coreservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import com.agent.GetInformation;

public class Application {

	// ///////////////////////////////////////////////////////////////////////////////////
	private static Application app = null;
	private int listenerPort = -1; 
	
	
	/**
	 * get single instance of this class
	 */
	public static synchronized Application getInstance() {
		if (app == null) {
			app = new Application();
		}
		return app;
	}

	public Application() {
	}


	DateFormat dateFormatter = new SimpleDateFormat("yyyy.MMMMM.dd hh:mm aaa");
	
	public void initListenerPort() {
		listenerPort = PortUtils.getFreePort(
				ServerConst.HARNESS_LISTENER_PORT_RANGE1, 
				ServerConst.HARNESS_LISTENER_PORT_RANGE2);
	}
	
	public void setListenerPort(int port){
		this.listenerPort = port;
	}

	public int getListenerPort(){
		return listenerPort;
	}
	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	public void startListener(int port) {
		ServerSocket listener = null;
		try {
			
			listener = new ServerSocket(port);
			
			while(true){
				Socket currentSocket = listener.accept();
				new Handler(currentSocket).start();
			}
			
			
            //new Handler(listener.accept()).start();
            //new Handler(listener.accept());
        } catch(Exception ex){
        	ex.printStackTrace();
        }
		finally {
            try {
				listener.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
	}

	
	/**
     * A handler thread class.  Handlers are spawned from the listening
     * loop and are responsible for a dealing with a single client
     * and broadcasting its messages.
     */
    private static class Handler extends Thread {
        private Socket socket;
        private BufferedReader in;
        private PrintWriter out;

        /**
         * Constructs a handler thread, squirreling away the socket.
         * All the interesting work is done in the run method.
         */
        public Handler(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            try {
                // Accept messages from this client and broadcast them.
               // while (true) {
                	// Create character streams for the socket.
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    out = new PrintWriter(socket.getOutputStream(), true);
                    String message = in.readLine();
                    System.out.println("handle message: " + message);
                    if (message != null) {
                         String[] infor = message.split("@##@");
                         if(infor!=null && infor.length>=2){
                        	 String title = infor[0];
                        	 String actionName = infor[1];
                        	 GetInformation inforInstance = new GetInformation(); 
                        	 String result = "";
                        	 if(actionName.equalsIgnoreCase("getChildren")){
                        		 result = inforInstance.getChildren(title);
                        		 result = "getChildren" + "\t" + result;
                        	 } 
                        	 else if(actionName.equalsIgnoreCase("getSupportedProperty")){
                        		 if(infor.length>=3){
                        			 String control = infor[2];
                        			 result = inforInstance.getProperties(title, control);
                        			 result = "getSupportedProperty" + "\t" + result;
                        		 } 
                        	 } 
                        	 else if(actionName.equalsIgnoreCase("getProperty")){
                        		 if(infor.length>=4){
                        			 String control = infor[2];
                        			 String propertyName = infor[3];
                        			 result = inforInstance.getProperty(title, control, propertyName);
                        			 result = "getProperty" + "\t" + result;
                        		 }
                        	 }
                        	 
                        	 //save result
                        	 Utilities.saveFile("result.txt", result, false);
                         }
                  //  }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                	out.flush();
        			//closing the in & out streams
        			out.close();
        			in.close();
                    socket.close();
                } catch (IOException e) {
                }
            }
        }
    }
	
}
